const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const path = event.path;
  const timestamp = event.timestamp;
  const wxContext = cloud.getWXContext()

  
  if(typeof timestamp !== "number")
  {
      return {
        code:400,
        data:{},
        msg:"wrong param"
      }
  }
  
  if(timestamp%3600000 != 0)
  {
    return {
      code:400,
      data:{},
      msg:"wrong param"
    }
  }

    
  const res = await db.collection("user").where({openid:wxContext.OPENID,status:"0"}).get()

  if(res.data.length == 0)
  {
      return {
        code:401,
        data:{},
        msg:"no privilege"
      }
  }
  else
  {
    const resu = await db.collection("QRcode").where({timestamp:timestamp}).get()
    if(resu.data.length == 0)
    {
      const resul = await db.collection("QRcode").add({data:{
        timestamp:timestamp,
        path:path
      }
    })
      if(resul.errMsg == "collection.add:ok")
      {
        return {
          code:200,
          data:{
            type:"insert",
            errMsg:resul.errMsg
          },
          msg:"success"
        }
      }
      else
      {
        return {
          code:500,
          data:{errMsg:resul.errMsg},
          msg:"fail"
        }
      }
    }
    else
    {
      const result = await db.collection("QRcode").doc(resu.data[0]._id).update({
        data:{
          path:path,
        }
      })
      console.log(result)
      let updated = result.stats.updated
      if(updated == 0)
      {
        return {
          code:404,
          data:{
            updated:updated
          },
          msg:"not change"
        }
      }
      else
      {
        return {
          code:200,
          data:{
            type:"update",
            updated:updated,
          },
          msg:"success"
        }
      }
    }
  }
};
